const mongoose = require("mongoose");
const path = require("path");

const TaskAttachmentSchema = new mongoose.Schema(
  {
    task: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Task",
      required: true,
    },
    // 关联的进度记录（可选）
    progress: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "TaskProgress",
      default: null,
    },
    uploadedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    // 原始文件名
    originalName: {
      type: String,
      required: true,
      trim: true,
    },
    // 存储的文件名
    fileName: {
      type: String,
      required: true,
      trim: true,
    },
    // 文件路径（相对于uploads目录）
    filePath: {
      type: String,
      required: true,
      trim: true,
    },
    // 文件大小（字节）
    fileSize: {
      type: Number,
      required: true,
      min: 0,
    },
    // MIME类型
    mimeType: {
      type: String,
      required: true,
      trim: true,
    },
    // 文件扩展名
    extension: {
      type: String,
      trim: true,
    },
    // 文件描述
    description: {
      type: String,
      trim: true,
      maxlength: 500,
      default: "",
    },
    // 文件分类
    category: {
      type: String,
      enum: ["document", "image", "video", "audio", "archive", "other"],
      default: "other",
    },
    // 是否已删除
    isDeleted: {
      type: Boolean,
      default: false,
    },
    // 下载次数
    downloadCount: {
      type: Number,
      default: 0,
    },
    // 额外元数据
    metadata: {
      type: mongoose.Schema.Types.Mixed,
      default: {},
    },
  },
  { timestamps: true }
);

// 索引优化
TaskAttachmentSchema.index({ task: 1, isDeleted: 1 });
TaskAttachmentSchema.index({ uploadedBy: 1, createdAt: -1 });
TaskAttachmentSchema.index({ category: 1 });
TaskAttachmentSchema.index({ mimeType: 1 });

// 虚拟字段：文件URL
TaskAttachmentSchema.virtual("url").get(function () {
  return `/api/attachments/${this._id}/download`;
});

// 虚拟字段：文件大小（人类可读）
TaskAttachmentSchema.virtual("fileSizeFormatted").get(function () {
  const bytes = this.fileSize;
  if (bytes === 0) return "0 Bytes";

  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
});

// 静态方法：根据文件扩展名确定分类
TaskAttachmentSchema.statics.getCategoryFromExtension = function (extension) {
  const ext = extension.toLowerCase();

  const imageExts = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg"];
  const videoExts = [".mp4", ".avi", ".mov", ".wmv", ".flv", ".webm", ".mkv"];
  const audioExts = [".mp3", ".wav", ".flac", ".aac", ".ogg", ".wma"];
  const archiveExts = [".zip", ".rar", ".7z", ".tar", ".gz", ".bz2"];
  const docExts = [
    ".pdf",
    ".doc",
    ".docx",
    ".xls",
    ".xlsx",
    ".ppt",
    ".pptx",
    ".txt",
    ".rtf",
  ];

  if (imageExts.includes(ext)) return "image";
  if (videoExts.includes(ext)) return "video";
  if (audioExts.includes(ext)) return "audio";
  if (archiveExts.includes(ext)) return "archive";
  if (docExts.includes(ext)) return "document";

  return "other";
};

// 确保虚拟字段在JSON序列化时包含
TaskAttachmentSchema.set("toJSON", { virtuals: true });

const TaskAttachment = mongoose.model("TaskAttachment", TaskAttachmentSchema);

module.exports = TaskAttachment;
